package dev.alm.cqtakeoutservice.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws")
@Slf4j
public class WebSocketServer {

    // 存放会话对象
    private static final Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        String sid = session.getId();
        log.info("客户端：" + sid + " 建立了连接");
        sessionMap.put(sid, session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自客户端：" + session.getId() + " 的信息：" + message);
    }

    @OnClose
    public void onClose(Session session) {
        String sid = session.getId();
        sessionMap.remove(sid);
        log.info("客户端：" + sid + " 已断开连接");
    }

    // 发送消息
    public void sendMessage(String message, Session session) {
        String sid = session.getId();
        // 给 sid 发送消息
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 群发
    public void sendMessageToAllClients(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            sendMessage(message, session);
        }
    }



}
